<script setup>
  import { onMounted, ref } from 'vue'
  import {
    onLoad,
    onShow,
    onReachBottom,
    onPullDownRefresh,
    onShareAppMessage,
  } from '@dcloudio/uni-app'
  import { http } from '@/utils/http.js'
  import { parseTime } from '@/utils/index.js'
  import { useUsercodeStore } from '@/store/usercode.js'
  import PayBox from '../../components/PayBox.vue'
  const createOrderUrl = ref('createBoxOrder_special')

  // 盲盒详情
  const blindboxId = ref()
  const goodsList = ref()
  const boxDetail = ref()
  const progressPercent = ref()
  async function getblindboxDetail() {
    const res = await http.request({
      url: '/api/box/boxDetails',
      method: 'POST',
      data: {
        id: blindboxId.value,
        case_id: 0,
      },
    })
    // console.log(res)
    goodsList.value = res.data.goods_info
    boxDetail.value = res.data.box
    progressPercent.value =
      Number(boxDetail.value.leftover) / Number(boxDetail.value.extract_ci)
    // console.log(progressPercent.value)
  }

  // 奖品详情弹出层
  const detailpopup = ref()
  const detailInfo = ref({ goods_name: '' })
  function checkDetail(item) {
    detailInfo.value = item
    detailpopup.value.open('bottom')
  }

  // 选择优惠券
  // 优惠券
  const couponId = ref(0)
  const couponname = ref('')
  const couponType = ref(-1)
  function chooseCoupon() {
    uni.navigateTo({
      url: `/drawPage/choosecoupon/index?money=${paymoney.value}&id=${blindboxId.value}&couponid=${couponId.value}`,
    })
  }

  //动态背景

  // 支付
  const paypopup = ref()
  const paypopupBool = ref(false)
  const paymoney = ref()
  //有优惠券的jiage
  const realmoney = ref()
  const buyCount = ref(0)
  // const agree = ref(true)
  async function payPOP(count) {
    const userCodeStore = useUsercodeStore()
    if (
      userCodeStore.usercode.token == '' ||
      userCodeStore.usercode.userId == ''
    ) {
      uni.utils.toast('为了让您有更好的体验，请先登录')
      setTimeout(() => {
        uni.navigateTo({
          url: `/pages/login/login`,
        })
      }, 2000)
      return
    }
    // await getUserMoney()
    paypopup.value.open('bottom')
    paypopupBool.value = true
    paymoney.value = (boxDetail.value.price * count).toFixed(2)
    // 每次点击重新选择优惠券
    realmoney.value = paymoney.value
    couponId.value = 0
    couponname.value = ''
    buyCount.value = count
  }

  //支付radio
  const currentradio = ref(3)

  function radioChange(evt) {
    currentradio.value = evt.detail.value
  }
  function payReturnFun(res) {
    // console.log(res)
    if (res.st == 1) {
      paypopup.value.close()
      paypopupBool.value = false
      toactivity(res)
    } else if (res.st == -2) {
      namepopup.value.open('center')
    } else {
      uni.utils.toast(res.msg)
    }
  }
  function toactivity(res) {
    haveDraw.value = res.data.box_goods
    uni.navigateTo({
      url: `/drawPage/treasureDrawCards/index?thecard=${encodeURIComponent(
        JSON.stringify(haveDraw.value)
      )}&num=${buyCount.value}&id=${blindboxId.value}&pay_type=${
        currentradio.value
      }&money=${paymoney.value}&img=${boxDetail.value.img}&name=${
        boxDetail.value.name
      }&couponid=${couponId.value}&order_id=${
        res.data.order_id
      }&&energy_info=${JSON.stringify(res.data.energy_info)}&is_flip=${
        res.data.is_flip
      }`,
    })
  }
  // 跳转抽卡

  function goRealName() {
    namepopup.value.open('center')
    uni.navigateTo({
      url: '/minePage/authentication/index',
    })
  }

  // 获取订单id
  const orderId = ref()
  const namepopup = ref()

  // 寻宝抽奖
  const haveDraw = ref([])
  // 星石支付

  // // 微信支付

  // 微信支付
  //轮询微信支付订单状态
  const timeStatu = ref(true)
  const paying = ref(1)

  //弹窗
  const popup = ref()
  const rule = ref()

  const openList = ref([])
  const opentPage = ref(1)
  async function getOpenList() {
    const res = await http.request({
      url: '/api/box/specialLog',
      method: 'POST',
      data: {
        page: opentPage.value,
        limit: 10,
        id: blindboxId.value,
      },
    })
    // console.log(res)
    openList.value = [...openList.value, ...res.data]
  }

  function getMoreOpen() {
    ++opentPage.value
    getOpenList()
  }

  async function openDetail() {
    opentPage.value = 1
    openList.value = []
    await getOpenList()
    popup.value.open('center')
  }
  // 规则
  const ruleStrings = ref('')
  async function getRules(id) {
    const res = await http.request({
      url: '/api/index/getDetails',
      method: 'POST',
      data: {
        id: id,
      },
    })
    // console.log(res)
    ruleStrings.value = res.data.details
  }
  async function openRule() {
    await getRules(9)
    rule.value.open('center')
  }
  function closeDetail() {
    popup.value.close()
  }
  function closeRule() {
    rule.value.close()
  }

  onShareAppMessage(() => {
    const userCodeStore = useUsercodeStore()
    const user = userCodeStore.usercode.user
    return {
      title: `${boxDetail.value.name} | ${
        boxDetail.value.price
      }一发 | 寻宝剩余${Math.floor(progressPercent.value * 100)}%`,
      path: `drawPage/treasureDraw/index?pid=${user}&id=${blindboxId.value}`,
    }
  })

  onLoad((option) => {
    blindboxId.value = option.id
    // animation()
  })
  onShow(() => {
    getblindboxDetail()
    uni.$once('thecoupon', (data) => {
      // console.log(data)
      realmoney.value = paymoney.value
      if (data.coupon) {
        couponId.value = data.coupon.id
        couponname.value = data.coupon.title
        // 满减
        if (data.coupon.type == 1) {
          realmoney.value = Number(
            (paymoney.value - data.coupon.money).toFixed(2)
          )
        } else if (data.coupon.type == 2) {
          realmoney.value = Number(
            (paymoney.value - data.coupon.money).toFixed(2)
          )
        } else if (data.coupon.type == 3) {
          realmoney.value = Number(
            (paymoney.value * data.coupon.discount).toFixed(2)
          )
        }
      }
    })
  })
</script>

<template>
  <view class="lucky-content">
    <!-- 头部动画 -->
    <view class="recharge">
      <image
        src="https://ojqn.wm2177.com/wechat_imgs/lucky/top-img.png"
        class="top-img"
      ></image>
      <image
        src="https://ojqn.wm2177.com/wechat_imgs/lucky/gif-img.gif"
        class="gif-img"
      ></image>
    </view>
    <!-- 规则记录 -->
    <view class="rule-detail">
      <view class="detail" @click="openDetail">
        <image
          src="https://ojqn.wm2177.com/wechat_imgs/lucky/detail.png"
        ></image>
        <text>开启记录</text>
      </view>
      <view class="detail" @click="openRule">
        <image src="https://ojqn.wm2177.com/wechat_imgs/lucky/rule.png"></image>
        <text>玩法规则</text>
      </view>
    </view>
    <!-- 下面 -->
    <view class="bottom">
      <view class="line">
        <image src="https://ojqn.wm2177.com/wechat_imgs/lucky/line.png"></image>
      </view>
      <view class="goods-list">
        <view class="title">
          <image
            src="https://ojqn.wm2177.com/wechat_imgs/lucky/title-img.png"
          ></image>
        </view>
        <scroll-view class="scroll-view_H" scroll-x="true" style="width: 91%">
          <view class="all-goods">
            <view
              class="goods-image"
              v-for="(item, index) in goodsList"
              :key="item.id"
              @click="checkDetail(item)"
            >
              <image :src="item.img"></image>
              <image
                v-if="item.rule_id == 28"
                src="https://ojqn.wm2177.com/wechat_imgs/lucky/lucky-icon-new.png"
                style="
                  position: absolute;
                  left: 0;
                  top: 0;
                  width: 102rpx;
                  height: 34rpx;
                "
                mode=""
              ></image>
              <view
                class=""
                style="
                  position: absolute;
                  top: 0;
                  right: 0;
                  padding: 10rpx;
                  font-size: 18rpx;
                  color: #fff;
                "
                v-if="item.goods_type == 1"
              >
                预售
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      <!-- 进度条 -->
      <view class="Progress">
        <view class="">
          <text class="">赏品数量剩余进度</text>
          <text class="" style="color: #fc83f0"
            >{{ Math.floor(progressPercent * 100) }}%</text
          >
          <text class="">（￥{{ boxDetail.price }}</text>
          <text class="">/抽）</text>
        </view>
        <view class="progress-bar">
          <view
            class="progress-bar-percent"
            :style="{
              width: `${Math.floor(progressPercent * 100)}%`,
            }"
          >
          </view>
          <!-- <image
						class="progress-front"
						:src="animationBG"
						:style="{
							left:
								progressPercent * 100 > 2
									? `${progressPercent * 100}%`
									: `2%`,
						}"
						mode=""
					></image> -->
        </view>
      </view>
      <!-- 按钮 -->
      <view class="select-button">
        <view class="one-select" @click="payPOP(1)">
          <image
            src="https://ojqn.wm2177.com/wechat_imgs/lucky/one.png"
          ></image>
        </view>
        <view class="ten-select" @click="payPOP(10)">
          <image
            src="https://ojqn.wm2177.com/wechat_imgs/lucky/ten.png"
          ></image>
        </view>
        <view class="three-select" @click="payPOP(3)">
          <image
            src="https://ojqn.wm2177.com/wechat_imgs/lucky/three.png"
          ></image>
        </view>
      </view>
    </view>

    <!-- 开启记录弹窗 -->
    <view>
      <uni-popup ref="popup" type="center">
        <view class="detail-pop">
          <view class="detail-img">
            <image
              src="https://ojqn.wm2177.com/wechat_imgs/lucky/openDetail.png"
            ></image>
          </view>
          <view class="close-img" @click="closeDetail">
            <image
              src="https://ojqn.wm2177.com/wechat_imgs/lucky/close-img.png"
            ></image>
          </view>
          <!-- 记录 -->
          <scroll-view
            scroll-y="true"
            class="scroll-Y"
            style="height: 906rpx"
            @scrolltolower="getMoreOpen"
          >
            <view class="detail-list">
              <!-- 幸运看 -->
              <view
                class="top-big-goods"
                :class="{
                  luckyicon: item.rule_id == 28,
                  fontcolor: item.rule_id == 28,
                }"
                v-for="(item, index) in openList"
                :key="item.id"
              >
                <view
                  class="user-information"
                  :class="{ fontcolor: item.rule_id == 28 }"
                >
                  <image :src="item.himg"></image>
                  <text class="">{{
                    item.nickname.substring(0, 2) + '****'
                  }}</text>
                </view>
                <view class="lucky-icon" v-if="item.rule_id == 28">
                  <image :src="item.rule_img"></image>
                </view>
                <view class="goods-name" :class="{ fontcolor: item.id == 28 }">
                  <view class="name-over">{{ item.goods_name }}</view>
                  <image :src="item.goods_img"></image>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>
      </uni-popup>
    </view>
    <!-- 玩法规则弹窗 -->
    <view>
      <uni-popup ref="rule" type="center">
        <view class="detail-pop">
          <view class="detail-img">
            <image
              src="https://ojqn.wm2177.com/wechat_imgs/lucky/openRule.png"
            ></image>
          </view>
          <view class="close-img" @click="closeRule">
            <image
              src="https://ojqn.wm2177.com/wechat_imgs/lucky/close-img.png"
            ></image>
          </view>

          <scroll-view scroll-y="true" style="height: 61vh">
            <view
              style="
                width: 94%;
                margin: 0 auto;
                margin-top: 35rpx;
                color: #aca1ea;
                padding-bottom: env(safe-area-inset-bottom);
              "
              class=""
            >
              <rich-text :nodes="ruleStrings"></rich-text>
            </view>
          </scroll-view>
        </view>
      </uni-popup>
    </view>

    <!-- 支付弹出层 -->
    <uni-popup ref="paypopup" type="bottom">
      <PayBox
        v-if="paypopupBool"
        :couponname="couponname"
        :createOrderUrl="createOrderUrl"
        :realmoney="realmoney"
        :paymoney="paymoney"
        :couponId="couponId"
        :buyCount="buyCount"
        :blindboxId="blindboxId"
        @payReturnFun="payReturnFun"
        @chooseCoupon="chooseCoupon"
        :boxDetailInfo="boxDetail"
      ></PayBox>
    </uni-popup>

    <!-- 实名制出层 -->
    <uni-popup ref="namepopup" type="center">
      <view class="namepopup-content">
        <view class="namepopup-title"> 提示 </view>
        <view class="namepopup-content-tow">
          鉴于您是平台的优质用户，为了能给您提供更好的服务体验，请先完成实名制认证。</view
        >
        <view class="namepopup-button">
          <view class="" @click="namepopup.close('center')"> 再想一下 </view>
          <view class="" @click="goRealName"> 确认实名 </view>
        </view>
      </view>
    </uni-popup>

    <!-- 详情弹出层 -->
    <uni-popup ref="detailpopup" type="bottom">
      <view class="detailpopup-content">
        <view class="detailpop-title" v-if="detailInfo.rule_id != 28">
          {{
            `${detailInfo.goods_name}（单抽售价：${boxDetail.price}元，初始获得概率：${detailInfo.probability}%）本奖池初始商品总数${boxDetail.extract_ci}，奖池抽取过程中实际概率会发生变化`
          }}
        </view>
        <view class="detailpop-title" v-else>
          {{
            `${detailInfo.goods_name}（单抽售价：${boxDetail.price}元，宝藏开启后随机获得）本奖池初始商品总数${boxDetail.extract_ci}，奖池抽取过程中实际概率会发生变化`
          }}
        </view>
        <image
          :src="detailInfo.img"
          style="width: 668rpx; height: 668rpx"
          mode=""
        ></image>
      </view>
    </uni-popup>
  </view>
</template>

<style lang="scss" scoped>
  page {
    background-color: #030e22;
  }

  .lucky-content {
    background-color: #030e22;
    min-height: 100vh;

    .recharge {
      background: url(https://ojqn.wm2177.com/wechat_imgs/lucky/bgg.png);
      background-size: 100%;
      z-index: -1;
      color: #fff;
      width: 100%;
      height: 984rpx;

      // position: relative;
      .top-img {
        display: flex;
        z-index: 2;
        // justify-content: center;
        // margin-left: 130rpx ;
        padding: 50rpx 0rpx 0rpx 140rpx;
        width: 480rpx;
        height: 480rpx;
        position: relative;

        image {
          width: 477rpx;
          height: 439rpx;
        }
      }

      .gif-img {
        display: flex;
        margin: auto;
        width: 400rpx;
        height: 400rpx;
        position: absolute;
        top: 100rpx;
        left: 178rpx;

        image {
          width: 310rpx;
          height: 310rpx;
        }
      }
    }

    .rule-detail {
      position: fixed;
      top: 15rpx;
      right: 0;

      // background-color: #000;
      width: 130rpx;
      height: 300rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-evenly;

      .detail {
        font-size: 20rpx;
        color: #e2e5fd;
        text-align: center;
        display: flex;
        flex-direction: column;

        image {
          width: 72rpx;
          height: 68rpx;
          margin: 15rpx auto;
        }
      }
    }

    .bottom {
      // padding-top: 920rpx;
      margin-top: -106rpx;

      .line {
        width: 100%;

        image {
          width: 750rpx;
          height: 18rpx;
        }
      }

      .goods-list {
        display: flex;
        margin: 15rpx;

        .title {
          width: 66rpx;
          height: 164rpx;
          border: 2rpx solid #e7dafb;
          border-radius: 10rpx;
          background-color: #05132e;
          display: flex;
          flex-shrink: 0;

          image {
            margin: auto;
            width: 35rpx;
            height: 133rpx;
          }
        }

        .all-goods {
          margin-left: 14rpx;
          // height: 152rpx;
          // overflow: hidden;
          display: flex;

          // background-color: #e7dafb;
          .goods-image {
            position: relative;
            width: 150rpx;
            height: 150rpx;
            background-color: #05132e;
            border: 2rpx solid #95749a;
            border-radius: 18rpx;
            display: flex;
            margin: 5rpx;
            flex-shrink: 0;

            image {
              width: 110rpx;
              height: 110rpx;
              margin: auto;
            }
          }
        }
      }

      .Progress {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin: 30rpx auto;
        color: #e2e5fd;
        font-weight: 600;
        font-size: 24rpx;
        .progress-bar {
          position: relative;
          width: 650rpx;
          height: 20rpx;
          margin-top: 27rpx;
          border-radius: 10rpx;
          background-color: #05132e;
          .progress-bar-percent {
            position: absolute;
            top: 0;
            left: 0;
            height: 100%;
            border-radius: 10rpx;
            background: linear-gradient(-90deg, #ffa0f0, #f527e4, #ff96ef);
          }
          .progress-front {
            position: absolute;
            top: -116%;
            width: 151rpx;
            height: 63rpx;

            transform: translateX(-89%);
          }
        }
      }

      .select-button {
        width: 100%;
        // height: 165rpx;
        display: flex;
        // margin: 80rpx auto;
        position: fixed;
        bottom: 60rpx;
        justify-content: space-between;

        .one-select,
        .three-select {
          margin: auto;

          image {
            width: 189rpx;
            height: 83rpx;
          }
        }

        .ten-select {
          image {
            width: 256rpx;
            height: 113rpx;
          }
        }
      }
    }
  }
  .detail-pop {
    width: 670rpx;
    height: 940rpx;
    border: 3px solid transparent;
    border-radius: 16px;
    background-clip: padding-box, border-box;
    background-origin: padding-box, border-box;
    background-image: linear-gradient(to right, #030e22, #030e22),
      linear-gradient(
        180deg,
        #c1e2ed,
        #c0edee,
        #5d95a9,
        #6a867e,
        #933eb6,
        #6395b0,
        #8a8ea8,
        #a2879f,
        #bcd0ea,
        #9f7ad3,
        #c2e3ed
      );
    .detail-img {
      width: 288rpx;
      height: 113rpx;
      margin: -47rpx auto;
      position: relative;
      image {
        width: 288rpx;
        height: 89rpx;
      }
    }
    .close-img {
      width: 70rpx;
      height: 70rpx;
      display: flex;
      position: absolute;
      top: -28rpx;
      right: -20rpx;
      image {
        width: 63rpx;
        height: 63rpx;
      }
    }
    .detail-list {
      // display: flex;
      // flex-direction: column;
      color: #e2e5fd;
      margin: 20rpx auto;
      // height: 874rpx;
      // overflow: scroll;
      .top-big-goods,
      .luckyicon {
        width: 617rpx;
        height: 80rpx;
        background: #051129;
        border-radius: 6rpx;
        margin-top: 15rpx;
        display: flex;
        justify-content: space-between;
        margin: 15rpx auto;
      }
      .fontcolor {
        color: #1b103c;
      }
      .luckyicon {
        // margin: 22rpx auto;
        color: #1b103c;
        background-image: linear-gradient(180deg, #d8c1f7, #fdede2, #9fd8fa);
      }
      .user-information {
        display: flex;
        font-size: 20rpx;
        // color: #e2e5fd;
        margin: auto;
        align-items: center;

        image {
          width: 47rpx;
          height: 47rpx;
          border-radius: 20rpx;
          margin-right: 10rpx;
        }
      }
      .lucky-icon {
        width: 100rpx;
        height: 80rpx;
        display: flex;
        margin: auto;
        image {
          width: 92rpx;
          height: 31rpx;
          margin: auto;
        }
      }
      .goods-name {
        display: flex;
        font-size: 20rpx;
        // color: #e2e5fd;
        margin: auto;
        align-items: center;
        image {
          width: 46rpx;
          height: 46rpx;
          margin-left: 10rpx;
        }
        .name-over {
          width: 252rpx;

          display: -webkit-box;
          -webkit-line-clamp: 1; /* 限制为两行 */
          -webkit-box-orient: vertical;
          overflow: hidden; /* 隐藏超出部分 */
          text-overflow: ellipsis; /* 超出部分用省略号表示 */
          white-space: normal; /* 允许换行 */
          /* 你可能还想设置一些其他样式，比如宽度、字体大小等 */
        }
      }
    }
  }

  .namepopup-content {
    width: 600rpx;
    height: 404rpx;
    padding: 0 30rpx;
    box-sizing: border-box;
    border-radius: 36rpx;
    background-color: #fff;

    .namepopup-title {
      height: 114rpx;
      border-bottom: 1px solid #d8d8d8;
      text-align: center;
      font-size: 40rpx;
      line-height: 114rpx;
      color: black;
    }

    .namepopup-content-tow {
      height: 164rpx;
      padding-top: 32rpx;
      box-sizing: border-box;
      text-align: center;
      font-size: 28rpx;
      color: #9b9b9d;
    }

    .namepopup-button {
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: white;

      // margin-top: 26rpx;
      view {
        width: 234rpx;
        height: 80rpx;
        background-color: $all-color;
        border-radius: 40rpx;
        text-align: center;
        font-size: 26rpx;
        font-weight: 700;
        line-height: 80rpx;

        &:first-child {
          border: 2rpx solid $all-color;
          background-color: #fff;
          color: $all-color;
        }
      }
    }
  }

  .detailpopup-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 923rpx;
    padding: 46rpx 50rpx;
    box-sizing: border-box;
    background-color: #051129;
    .detailpop-title {
      margin-bottom: 34rpx;
      text-align: center;
      font-size: 34rpx;
      color: #e2e5fd;
    }
  }
</style>
